<template>
  <AuModal
    v-model="showModal"
    :title="t('expiry_manage.form.material_store_select')"
    width="60vw"
    :padding="false"
    @handleConfirm="modalConfirm"
  >
    <div class="flex cate-left h-[calc(60vh_+_54px)]">
      <CategoryComponent
        ref="cateRef"
        :show-all="true"
        @cateClick="cateClick"
      />

      <el-divider direction="vertical" class="!h-full" />

      <div class="w-[calc(100%_-_256px_-_17px)] h-full bg-white">
        <div :class="TITLE_CLASS">
          <div class="flex items-center">
            <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
            <div class="text-[#242930] text-sm ml-[10px]">
              {{ t("expiry_manage.form.material_list") }}
            </div>
          </div>

          <!--          <div class="w-1/3 min-w-[420px]">-->
          <!--            <AuForm-->
          <!--              ref="formRef"-->
          <!--              class="mat-btn"-->
          <!--              :formList="formList"-->
          <!--              @submit="search"-->
          <!--            />-->
          <!--          </div>-->
        </div>
        <div class="h-[60vh]">
          <AuTable ref="tableRef" v-bind="gridOption">
            <template #status_default="{ row }">
              <el-tag :type="row.materialStatus === 1 ? 'primary' : 'info'"
                >{{
                  row.materialStatus === 1
                    ? t("expiry_manage.form.enabled")
                    : t("expiry_manage.form.disabled")
                }}
              </el-tag>
            </template>
          </AuTable>
        </div>
      </div>
    </div>
  </AuModal>
</template>

<script setup lang="ts">
import { AuModal } from "@/components/AuModal";
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { AuForm } from "@/components/AuForm";
import { AuTable } from "@/components/AuTable";
import { TITLE_CLASS } from "@/views/expiry/material/materialManage/constants";
import {
  CategoryProp,
  expiryAdd,
  expiryAddList,
  expiryGetList,
  getMaterialDetList
} from "@/api/expiry/expiry";
import CategoryComponent from "@/views/expiry/material/materialVersion/components/CategoryComponent.vue";
import { cloneDeep } from "lodash-unified";
import { ObjectProps, PropDefines } from "@/components/AuTable/type";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { DEVICE_TYPE_ENUM } from "@/utils/constants";

interface Props {
  modelValue: boolean;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  (e: "update:modelValue", val: boolean): void;
  (e: "confirm"): void;
}>();

const { t } = useI18n();

const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const route = useRoute();
const categoryChoose = ref<CategoryProp>();
let tableDataSource = [];
const gridOption = reactive<PropDefines>({
  isServerPage: false,
  showCheckbox: true,
  showExportBtn: false,
  columns: [
    {
      field: "material_id",
      title: "expiry_manage.form.material_code",
      align: "center"
    },
    { field: "name", title: "expiry_manage.form.name" },
    // {
    //   field: "overdue_time",
    //   title: "效期",
    //   formatter: ({ cellValue }) => `${cellValue / 3600000}小时`
    // },
    { field: "note", title: "table.note" }
  ],
  actions: [],
  topTools: [],
  dataSource: [],
  // fetchConfig: {
  //   query: {
  //     service: (params: ObjectProps) => {
  //       return getMaterialDetList(params);
  //     },
  //     param: () => formRef.value.getFormData()
  //   }
  // },
  vxeTableConfig: {
    checkboxConfig: {
      // checkField: "isChecked",
      // indeterminateField: "isIndeterminate",
      labelField: "check",
      checkMethod: ({ row }) => {
        return row.age > 26;
      }
    }
  }
});
const cateCheckedList = {};
const cateCheckedNodeList: { [key: string]: ObjectProps[] } = {};

const cateRef = ref();
const tableRef = ref();

function filterCate(data: ObjectProps[], cate: number) {
  if (cate === 0) {
    return data;
  }
  return data.filter((item: ObjectProps) => item.type_id === cate);
}

async function getMatData() {
  getMaterialDetList({ size: 0 }).then(res => {
    tableDataSource = res.data
      .map(v => {
        return {
          ...v,
          matId: v.material_id,
          materialSource: DEVICE_TYPE_ENUM.CABINET
        };
      })
      .filter(v => v.publish_status == 1);

    // tableDataSource = handleMatWithExpiry(resExpiry, cloneDeep(concatList));
    nextTick(() => {
      cateRef.value?.cateClick();
    });
  });

  const res = await expiryGetList({
    versionId: route.query.versionId,
    size: 0
  });
  if (res.data) {
    const mats = res.data.map(v => v.materialId);
    gridOption.vxeTableConfig.checkboxConfig = {
      // labelField: "index",
      checkMethod: ({ row }) => {
        return !mats.includes(row.material_id);
      }
      // visibleMethod({ row }) {
      //   return !mats.includes(row.material_id);
      // }
    };
  }
}

function setCheckedRows(rows: ObjectProps[], checked: boolean) {
  const $grid = tableRef.value.vxeGridRef;
  $grid.setCheckboxRow(rows, checked);
}

const cateClick = (item: CategoryProp) => {
  checkboxChange(categoryChoose.value);
  categoryChoose.value = item;
  gridOption.dataSource = filterCate(cloneDeep(tableDataSource), item.id);

  if (cateCheckedList[item.name]) {
    const filteredData = gridOption.dataSource.filter(v =>
      cateCheckedList[item.name].includes(v.matId)
    );
    setCheckedRows(filteredData, true);
  }
};

const checkboxChange = (category: CategoryProp) => {
  const list = tableRef.value.getCheckboxRecords();
  if (category) {
    cateCheckedList[category.name] = list.map(v => v.matId);
    cateCheckedNodeList[category.name] = list;
  }
};

const modalConfirm = async () => {
  cateClick(categoryChoose.value);
  const checkedList = [];
  for (const key in cateCheckedNodeList) {
    checkedList.push(...cateCheckedNodeList[key]);
  }
  if (!checkedList.length) {
    ElMessage.error(t("expiry_manage.form.select_material"));
    return;
  }
  const versionId = route.query.versionId;

  console.log(checkedList, versionId);
  // for (const item of checkedList) {
  //   const param = {
  //     materialId: item.matId,
  //     versionId,
  //     materialSource: item.materialSource,
  //     expiryList: [
  //       {
  //         title: "标题",
  //         expiryType: "1",
  //         expiryTime: 60
  //       }
  //     ]
  //   };
  // }
  const param = {
    versionId,
    expiryList: checkedList.map(v => ({
      versionId,
      materialId: v.matId,
      materialSource: v.materialSource,
      expiryType: "1",
      expiryTime: 0,
      isDefault: 1,
      startActiveTime: "",
      endActiveTime: "",
      storageMethod: "常温",
      title: "标题"
    }))
  };
  await expiryAddList(param);
  emit("update:modelValue", false);
  emit("confirm");
};

watch(
  () => props.modelValue,
  val => {
    if (val) {
      getMatData();
    }
  }
);
</script>

<style scoped lang="scss">
.cate-left {
  :deep(.scroll-height) {
    height: calc(60vh - 5vmin) !important;
  }
}
</style>
